package com.example.weather_news.activity;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.weather_news.R;
import com.example.weather_news.db.SaveCityInfo;
import com.example.weather_news.fragment.Fragment_Mine;
import com.example.weather_news.fragment.Fragment_News;
import com.example.weather_news.fragment.Fragment_Weather;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    private FrameLayout frame_main;
    private RadioButton rb_weather;
    private RadioButton rb_news;
    private RadioButton rb_mine;
    private RadioGroup rg_main;

    private String[] strs = new String[]{"frag_weather", "frag_news", "frag_mine"};
    private List<Fragment> frags = new ArrayList<Fragment>();
    ;
    private Fragment mFragment;
    private FragmentManager fm;
    private long firstTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        int a = DataSupport.findAll(SaveCityInfo.class).size();
        if (a == 0) {
            SaveCityInfo info = new SaveCityInfo();
            info.setCityName("睢宁县");
            info.save();
        }
        fm = getSupportFragmentManager();
        initFragment();

        initView();
        rb_weather.setChecked(true);
    }

    private void initFragment() {
        Fragment_Weather weather = new Fragment_Weather();
        Fragment_News news = new Fragment_News();
//        Fragment_Mine mine = new Fragment_Mine();
        frags.add(0, weather);
        frags.add(1, news);
//        frags.add(2, mine);

        mFragment = weather;
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.frame_main, mFragment).commitAllowingStateLoss();
    }


    public void switchFragment(Fragment from, Fragment to, int position) {
        if (mFragment != to) {
            mFragment = to;
            FragmentTransaction ft = fm.beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                // 隐藏当前的fragment，add下一个到Activity中
                ft.hide(from).add(R.id.frame_main, to, strs[position]).commitAllowingStateLoss();
            } else {
                ft.hide(from).show(to).commitAllowingStateLoss();
            }
        }
    }

    /**
     * 当activity非正常销毁时会进入此方法中 保存一些临时性的数据
     *
     * @param outState
     * @param outPersistentState
     */
    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        stateCheck(outState);
    }

    /**
     * 状态检测 用于内存不足的时候保证fragment不会重叠
     *
     * @param outState
     */
    private void stateCheck(Bundle outState) {
        FragmentManager fm = getSupportFragmentManager();
        if (outState == null) {
            FragmentTransaction ft = fm.beginTransaction();
            mFragment = new Fragment_Weather();
            ft.add(R.id.frame_main, mFragment).commit();
        } else {
            //通过设置的tag来寻找fragment
            Fragment_Weather weather = (Fragment_Weather) fm.findFragmentByTag(strs[0]);
            Fragment_News news = (Fragment_News) fm.findFragmentByTag(strs[1]);
//            Fragment_Mine mine = (Fragment_Mine) fm.findFragmentByTag(strs[2]);
//            fm.beginTransaction().show(weather).hide(news).hide(mine).commitAllowingStateLoss();
            fm.beginTransaction().show(weather).hide(news).commitAllowingStateLoss();
        }
    }

    //解决Fragment重叠问题
//    @Override
//    protected void onRestoreInstanceState(Bundle savedInstanceState) {
//        super.onRestoreInstanceState(savedInstanceState);
//        for (int i = 0; i < rg_main.getChildCount(); i++) {
//            RadioButton mBtn = (RadioButton) rg_main.getChildAt(i);
//            FragmentManager fm = getSupportFragmentManager();
//            FragmentTransaction ft = fm.beginTransaction();
//            Fragment frag = fm.findFragmentByTag(String.valueOf(mBtn.getTag()));
//            if (frag != null) {
//                if (!mBtn.isChecked()) {
//                    ft.hide(frag);
//                }
//            }
//            ft.commit();
//        }
//    }


    private void initView() {
        frame_main = (FrameLayout) findViewById(R.id.frame_main);
        rb_weather = (RadioButton) findViewById(R.id.rb_weather);
        rb_news = (RadioButton) findViewById(R.id.rb_news);
//        rb_mine = (RadioButton) findViewById(R.id.rb_mine);
        rg_main = (RadioGroup) findViewById(R.id.rg_main);

        rg_main.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_weather:
                switchFragment(mFragment, frags.get(0), 0);
                break;
            case R.id.rb_news:
                switchFragment(mFragment, frags.get(1), 1);
                break;
//            case R.id.rb_mine:
//                switchFragment(mFragment, frags.get(2), 2);
//                break;
        }
    }

    //双击回退,退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - firstTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
